// pages/shopcart/shopcart.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    goodsList: {
      saveHidden: true,//显示完成按钮
      totalPrice: 0,  //选中总价格
      allSelect: true, //所有都选中
      noSelect: false, //没有选中任何商品
      list: [] //所有选中商品
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var shopList = [];

    // 获取购物车数据
    var shopCarInfoMem = wx.getStorageSync('shopCarInfo');

    //如果购物车有数据
    if (shopCarInfoMem && shopCarInfoMem.shopList) {
      shopList = shopCarInfoMem.shopList
    }

    this.data.goodsList.list = shopList;
    
    this.setGoodsList(this.getSaveHide(), this.totalPrice(), this.allSelect(),                this.noSelect(), shopList);
  },

//控制编辑和完成按钮的隐藏显示
  getSaveHide: function () {
    var saveHidden = this.data.goodsList.saveHidden;
    return saveHidden;
  },

 //计算总金额
  totalPrice: function () {
    var list = this.data.goodsList.list;
    var total = 0;
    for (var i = 0; i < list.length; i++) {
      var curItem = list[i];
      if (curItem.active) {
        total += parseFloat(curItem.price) * curItem.number;
      }
    }
    total = parseFloat(total.toFixed(2));//js浮点计算bug，取两位小数精度
    return total;
  },

  //全部选中标志
  allSelect: function () {
    var list = this.data.goodsList.list;
    var allSelect = false;
    for (var i = 0; i < list.length; i++) {
      var curItem = list[i];
      if (curItem.active) {
        allSelect = true;
      } else {
        allSelect = false;
        break;
      }
    }
    return allSelect;
  },

  //都没选中标志
  noSelect: function () {
    var list = this.data.goodsList.list;
    var noSelect = 0;
    for (var i = 0; i < list.length; i++) {
      var curItem = list[i];
      if (!curItem.active) {
        noSelect++;
      }
    }
    if (noSelect == list.length) {
      return true;
    } else {
      return false;
    }
  },

//返回新的购物车信息
  setGoodsList: function (saveHidden, total, allSelect, noSelect, list) {
    this.setData({
      goodsList: {
        saveHidden: saveHidden,
        totalPrice: total,
        allSelect: allSelect,
        noSelect: noSelect,
        list: list
      }
    });
    
   //总的购买数量
    var tempNumber = 0;
    for (var i = 0; i < list.length; i++) {
      tempNumber = tempNumber + list[i].number
    }
  
    var shopCarInfo = {};
    shopCarInfo.shopList = list;
    shopCarInfo.shopNum = tempNumber;

    wx.setStorage({
      key: "shopCarInfo",
      data: shopCarInfo
    })
  },

  //跳转到首页
  toIndexPage: function () {
    wx.switchTab({
      url: "/pages/index/index"
    });
  },

//选中或取消商品
  selectTap: function (e) {
    var index = e.currentTarget.dataset.index;//选中index
    var list = this.data.goodsList.list;

    //设置选中状态
    if (index) {
      list[parseInt(index)].active = !list[parseInt(index)].active;

      this.setGoodsList(this.getSaveHide(), this.totalPrice(), this.allSelect(),                this.noSelect(), list);
    }
  },

//全选按钮事件
  bindAllSelect: function () {
    var currentAllSelect = this.data.goodsList.allSelect;
    var list = this.data.goodsList.list;
    if (currentAllSelect) {
      for (var i = 0; i < list.length; i++) {
        var curItem = list[i];
        curItem.active = false;
      }
    } else {
      for (var i = 0; i < list.length; i++) {
        var curItem = list[i];
        curItem.active = true;
      }
    }

    this.setGoodsList(this.getSaveHide(), this.totalPrice(), !currentAllSelect,               this.noSelect(), list);
  },

//删除购物车商品（去掉选中的商品后返回剩余）
  deleteSelected: function () {
    var list = this.data.goodsList.list;
    list = list.filter(function (curGoods) {
      return !curGoods.active;
    });
    this.setGoodsList(this.getSaveHide(), this.totalPrice(), this.allSelect(),                this.noSelect(), list);
  },

//编辑购物车
  editTap: function () {
    var list = this.data.goodsList.list;
    for (var i = 0; i < list.length; i++) {
      var curItem = list[i];
      curItem.active = false;
    }
    this.setGoodsList(!this.getSaveHide(), this.totalPrice(), this.allSelect(),               this.noSelect(), list);
  },

//编辑完成
  saveTap: function () {
    var list = this.data.goodsList.list;
    for (var i = 0; i < list.length; i++) {
      var curItem = list[i];
      curItem.active = true;
    }
    this.setGoodsList(!this.getSaveHide(), this.totalPrice(), this.allSelect(),               this.noSelect(), list);
  },

//加数量
  jiaBtnTap: function (e) {
    var index = e.currentTarget.dataset.index;
    var list = this.data.goodsList.list;
    if (index) {
      if (list[parseInt(index)].number < 10) {
        list[parseInt(index)].number++;
        this.setGoodsList(this.getSaveHide(), this.totalPrice(), this.allSelect(),                this.noSelect(), list);
      }
    }
  },

  //减数量
  jianBtnTap: function (e) {
    var index = e.currentTarget.dataset.index;
    var list = this.data.goodsList.list;
    if (index) {
      if (list[parseInt(index)].number > 1) {
        list[parseInt(index)].number--;
        this.setGoodsList(this.getSaveHide(), this.totalPrice(), this.allSelect(),                this.noSelect(), list);
      }
    }
  },

//去结算
  toPayOrder: function () {
    wx.showLoading();
    var that = this;
    if (this.data.goodsList.noSelect) {
      wx.hideLoading();
      return;
    }

   //从缓存读取购物车信息
    var shopList = [];
    var shopCarInfoMem = wx.getStorageSync('shopCarInfo');

    //获取选中的商品
    if (shopCarInfoMem && shopCarInfoMem.shopList) {
      shopList = shopCarInfoMem.shopList.filter(entity => {
        return entity.active;
      });
    }
    
    if (shopList.length == 0) {
      wx.hideLoading();
      return;
    }

    var isFail = false;
    var doneNumber = 0;
    var needDoneNUmber = shopList.length;
    for (let i = 0; i < needDoneNUmber; i++) {
            if (isFail) {
              wx.hideLoading();
              return;
            }
            let carShopBean = shopList[i];
            // 获取价格和库存
            if (!carShopBean.propertyChildIds || carShopBean.propertyChildIds == "") {
              wx.request({
                url: 'https://api.it120.cc/tz/shop/goods/detail',
                data: {
                  id: carShopBean.goodsId
                },
                success: function (res) {
                  doneNumber++;
                  //没有规格，表示商品已失效
                  if (res.data.data.properties) {
                    wx.showModal({
                      title: '提示',
                      content: res.data.data.basicInfo.name + ' 商品已失效，请重新购买',
                      showCancel: false
                    })
                    isFail = true;
                    wx.hideLoading();
                    return;
                  }

                  if (res.data.data.basicInfo.stores < carShopBean.number) {
                    wx.showModal({
                      title: '提示',
                      content: res.data.data.basicInfo.name + ' 库存不足，请重新购买',
                      showCancel: false
                    })
                    isFail = true;
                    wx.hideLoading();
                    return;
                  }
                  if (res.data.data.basicInfo.minPrice != carShopBean.price) {
                    wx.showModal({
                      title: '提示',
                      content: res.data.data.basicInfo.name + ' 价格有调整，请重新购买',
                      showCancel: false
                    })
                    isFail = true;
                    wx.hideLoading();
                    return;
                  }
                  if (needDoneNUmber == doneNumber) {
                    that.navigateToPayOrder();
                  }
                }
              })
            } else {
              wx.request({
                url: 'https://api.it120.cc/tz/shop/goods/price',
                data: {
                  goodsId: carShopBean.goodsId,
                  propertyChildIds: carShopBean.propertyChildIds
                },
                success: function (res) {
                  doneNumber++;
                  if (res.data.data.stores < carShopBean.number) {
                    wx.showModal({
                      title: '提示',
                      content: carShopBean.name + ' 库存不足，请重新购买',
                      showCancel: false
                    })
                    isFail = true;
                    wx.hideLoading();
                    return;
                  }
                  if (res.data.data.price != carShopBean.price) {
                    wx.showModal({
                      title: '提示',
                      content: carShopBean.name + ' 价格有调整，请重新购买',
                      showCancel: false
                    })
                    isFail = true;
                    wx.hideLoading();
                    return;
                  }
                  if (needDoneNUmber == doneNumber) {
                    that.navigateToPayOrder();
                  }
                }
              })
            }

    }
  },

  navigateToPayOrder: function () {
    wx.hideLoading();
    wx.navigateTo({
      url: "/pages/to-pay-order/to-pay-order"
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
  
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
  
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
  
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
  
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
  
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
  
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
  
  }
})